<template>
  <div>
    <!-- 触发按钮 -->
    <slot name="trigger" :exportPDF="handleExport" :loading="isGenerating">
      <v-btn :loading="isGenerating" :disabled="isGenerating" elevation="0" color="#39c464" class="text-white"
        @click="handleExport">
        <i class="fa fa-download mr-2"></i>
        {{ isGenerating ? '生成中...' : buttonText }}
      </v-btn>
    </slot>

    <!-- 进度条 -->
    <v-progress-linear v-if="showProgress && isGenerating" v-model="progress" color="primary" height="4"
      class="mt-2"></v-progress-linear>

    <!-- 内容插槽 -->
    <div v-show="false" ref="pdfContainer">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { usePDFExport, type PDFExportOptions } from '~/composables/usePDFExport'

interface Props {
  filename?: string
  options?: PDFExportOptions
  buttonText?: string
  showProgress?: boolean
  selector?: string
  componentRef?: HTMLElement
}

const props = withDefaults(defineProps<Props>(), {
  filename: '导出文件',
  buttonText: '导出为PDF',
  showProgress: true,
})

const emit = defineEmits<{
  exportStart: []
  exportSuccess: [result: any]
  exportError: [error: string]
}>()

const pdfContainer = ref<HTMLElement>()
const { isGenerating, progress, exportToPDF, exportBySelector } = usePDFExport()

const handleExport = async () => {
  try {
    emit('exportStart')

    let result

    if (props.selector || props.componentRef) {
      console.log('使用选择器导出', props.componentRef?.$el)
      // 使用选择器导出
      result = await exportBySelector(props.selector || (props.componentRef?.$el ?? props.componentRef), {
        filename: props.filename,
        ...props.options,
      })
    } else if (pdfContainer.value) {
      // 使用容器导出
      result = await exportToPDF(pdfContainer.value, {
        filename: props.filename,
        ...props.options,
      })
    } else {
      throw new Error('未指定导出内容')
    }

    if (result.success) {
      emit('exportSuccess', result)
    } else {
      emit('exportError', result.error || '导出失败')
    }
  } catch (error) {
    emit('exportError', error instanceof Error ? error.message : '导出失败')
  }
}

// 暴露方法给父组件
defineExpose({
  exportPDF: handleExport,
})
</script>